package com.jrfid.smartcabinet.demo.base

import android.app.Application
import android.database.DatabaseUtils
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.databinding.DataBindingUtil
import androidx.databinding.ViewDataBinding
import androidx.fragment.app.Fragment
import androidx.fragment.app.viewModels
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.ViewModelProviders
import androidx.navigation.fragment.findNavController
import com.jrfid.smartcabinet.demo.BR

/**
 * author: shihao
 * date: 2021/3/11 14:58
 * description:
 */
abstract class BaseFragment<VB : ViewDataBinding, VM : BaseViewModel>(clazz: Class<VM>) : Fragment() {
    val TAG: String = this.javaClass.simpleName


    private var dataBinding: VB? = null
    private var viewModel: VM? = null
    private var viewModelClass: Class<VM> = clazz

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        var rootView: View? = null
        getLayoutId()?.let {
            dataBinding = DataBindingUtil.inflate(inflater, it, container, false)
            rootView = dataBinding!!.root
        }
        getLayoutView()?.let {
            rootView = it
            dataBinding = DataBindingUtil.bind(it)
        }
        viewModel = ViewModelProvider(this, BaseViewModelFactory.getInstance(requireActivity().application, findNavController()))[viewModelClass]
        return rootView
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        viewModel?.let {
            lifecycle.addObserver(it)
        }
        dataBinding?.setVariable(BR.viewModel, viewModel)
//        if (useEventBus()) {
//            EventBus.getDefault().register(this)
//        }
    }

    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)
        setData()
    }

    override fun onDestroy() {
        super.onDestroy()
        dataBinding = null
//        if (useEventBus()) {
//            EventBus.getDefault().unregister(this)
//        }
        viewModel?.let {
            lifecycle.removeObserver(it)
        }
    }

    open fun useEventBus(): Boolean {
        return false
    }

    open fun getLayoutId(): Int? {
        return null
    }

    open fun getLayoutView(): View? {
        return null
    }

    fun getDataBinding(): VB? = dataBinding

    fun getViewModel(): VM? = viewModel

    abstract fun setData()

    fun getStringFormat(resId: Int, vararg formatArgs: Any): String {
        return resources.getString(resId, *formatArgs)
    }
}